package org.xue.snowmall.seckill.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.xue.snowmall.common.utils.PageUtils;
import org.xue.snowmall.common.utils.Query;

import org.xue.snowmall.common.utils.R;
import org.xue.snowmall.seckill.dao.SeckillRecordDao;
import org.xue.snowmall.seckill.entity.SeckillRecordEntity;
import org.xue.snowmall.seckill.entity.SeckillSessionEntity;
import org.xue.snowmall.seckill.service.SeckillRecordService;
import org.xue.snowmall.seckill.service.SeckillSessionService;
import org.xue.snowmall.seckill.vo.RelationVo;


@Service("seckillRecordService")
public class SeckillRecordServiceImpl extends ServiceImpl<SeckillRecordDao, SeckillRecordEntity> implements SeckillRecordService {

    @Autowired
    private SeckillSessionService seckillSessionService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SeckillRecordEntity> page = this.page(
                new Query<SeckillRecordEntity>().getPage(params),
                new QueryWrapper<SeckillRecordEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public R saveSeckillRecord(List<RelationVo> vo) {


        //根据sessionId获取场次信息
        Long gsmSeckillSessionId = vo.get(0).getGsmSeckillSessionId();
        SeckillSessionEntity seckillSessionEntity = seckillSessionService.getById(gsmSeckillSessionId);
        List<SeckillRecordEntity> collect = vo.stream().map(item -> {
            SeckillRecordEntity seckillRecordEntity = new SeckillRecordEntity();
            BeanUtils.copyProperties(item, seckillRecordEntity);
            seckillRecordEntity.setGsmSeckillRecordStatus("0");
            seckillRecordEntity.setGsmSeckillSessionName(seckillSessionEntity.getGsmSeckillSessionName());
            return seckillRecordEntity;
        }).collect(Collectors.toList());
        this.saveBatch(collect);
        return R.ok();
    }

    @Override
    public List<SeckillRecordEntity> uploadGoods() {

        String goods = redisTemplate.opsForValue().get("goods");
        if (goods != null) {
            return JSON.parseObject(goods, new TypeReference<List<SeckillRecordEntity>>() {
            });
        }
        return null;
    }

    //定时任务实现上架最近三天的秒杀商品
    @Scheduled(cron = "0 */5 * * * ?")
    public void uploadThreeDaysGoods() {
        findThreeDaysGoods();
    }

    private void findThreeDaysGoods() {
        //找出最近三天的秒杀活动
        List<SeckillSessionEntity> gsmSeckillSession = seckillSessionService.list(new QueryWrapper<SeckillSessionEntity>().between("gsm_seckill_session_start_time", startTime(), endTime()));
        //找出当前活动的商品有哪些
        if (gsmSeckillSession != null && gsmSeckillSession.size() > 0) {
            String ids = "";
            for (SeckillSessionEntity seckillSessionEntity : gsmSeckillSession) {
                ids += "," + seckillSessionEntity.getGsmSeckillSessionId();
            }
            String substring = ids.substring(1);
            String[] split = substring.split(",");
            List<Long> BatchId = new ArrayList<>();
            for (String s : split) {
                BatchId.add(new Long(s));
            }
            List<SeckillRecordEntity> seckillRecordEntities = baseMapper.selectBatchIds(BatchId);

            //将查到的值放入redis中
            redisTemplate.opsForValue().set("goods", JSON.toJSONString(seckillRecordEntities));
        }
    }


    private String startTime() {
        LocalDate now = LocalDate.now();
        LocalTime min = LocalTime.MIN;
        LocalDateTime startTime = LocalDateTime.of(now, min);
        return startTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

    private String endTime() {
        LocalDate now = LocalDate.now();
        LocalDate localDate1 = now.plusDays(2);
        LocalTime max = LocalTime.MAX;
        LocalDateTime endTime = LocalDateTime.of(localDate1, max);

        return endTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }
}